package com.zhkjnet.zhyy.interceptor;

import com.zhkjnet.zhyy.bean.RequiredPermission;
import com.zhkjnet.zhyy.bean.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecurityInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpSession session;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取权限注解
            RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
            if (requiredPermission != null) {
                Roles role = (Roles) session.getAttribute("role");
                boolean hasRole = hasRole(requiredPermission, role);
                //有权限
                if (hasRole) return true;
                //跳转到登陆
                switch (requiredPermission.value()[0]) {
                    case User:
                        response.sendRedirect(request.getContextPath() + "/login");
                        break;
                    case Admin:
                        response.sendRedirect(request.getContextPath() + "/admin/login");
                        break;
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean hasRole(RequiredPermission requiredPermission, Roles target) {
        for (Roles roleEnum : requiredPermission.value()) {
            if (roleEnum == target) return true;
        }
        return false;
    }
}
